﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Configuration;
using Newtonsoft.Json;
using System.IO;
using UcAsp.Models;
namespace UcAsp.Controllers
{
    public class OpenLoginController : Controller
    {
        //
        // GET: /OpenLogin/
        private UcAspNetEntities entities = new UcAspNetEntities();
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult QQ()
        {
            string Code = Request.QueryString["code"];
            string logintext = UcAsp.WorkFrame.UcAspWebClient.GetString("https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=" + ConfigurationManager.AppSettings["QQAPPID"] + "&client_secret=" + ConfigurationManager.AppSettings["QQAPPKEY"] + "&code=" + Code + "&state=&redirect_uri=" + ConfigurationManager.AppSettings["QQRedirect"] + "");           
            string[] token=logintext.Split('&');
            string openid = UcAsp.WorkFrame.UcAspWebClient.GetString("https://graph.qq.com/oauth2.0/me?access_token=" + token[0].Split('=')[1] + "").Replace("callback( ", "").Replace(" )", "");
            JsonReader json = new JsonTextReader(new StringReader(openid));
            JsonSerializer serializer = new JsonSerializer();
            UcAsp.Models.OpenID open = (UcAsp.Models.OpenID)serializer.Deserialize(json, typeof(UcAsp.Models.OpenID));
            string userinfo = UcAsp.WorkFrame.UcAspWebClient.GetString("https://graph.qq.com/user/get_user_info?access_token=" + token[0].Split('=')[1] + "&oauth_consumer_key=" + ConfigurationManager.AppSettings["QQAPPID"] + "&openid=" + open.openid + "");
            JsonReader userjson = new JsonTextReader(new StringReader(userinfo.Replace("\\","").Replace("\n","")));
            UcAsp.Models.QQUser qquser = (UcAsp.Models.QQUser)serializer.Deserialize(userjson, typeof(UcAsp.Models.QQUser));
            UcAsp.Models.UserInfo info = entities.UserInfos.FirstOrDefault(o=>o.OpenID==open.openid);
            if (info == null)
            {

                info = new Models.UserInfo { Point = Convert.ToInt32(UcAsp.WorkFrame.SettingConfig.GetSiteSetting.PointsRate), LoginIP = Request.UserHostAddress, RecommendID = 0, UserPassword = token[0].Split('=')[1], OpenID = open.openid, UserName = qquser.nickname, Logo = qquser.figureurl_qq_2, SessionID = Session.SessionID, LoginTime = DateTime.Now };
                entities.UserInfos.Add(info);
                int id = entities.SaveChanges();
                Session["Info"] = "User";
                Session["ID"] = id.ToString();
                Session["UserName"] = info.UserName;

            }
            else
            {
                Session["Info"] = "User";
                Session["ID"] = info.ID;
                Session["UserName"] = info.UserName;
                info.UserPassword = token[0].Split('=')[1];
                info.OpenID = open.openid;
                info.Point = info.Point + 10;
                entities.SaveChanges();
            }
            return Redirect("/User/Home");
        }
        public ActionResult Weibo()
        {
            string Code = Request.QueryString["code"];
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("client_id", ConfigurationManager.AppSettings["WAPPID"]);
            param.Add("client_secret", ConfigurationManager.AppSettings["WAPPKEY"]);
            param.Add("grant_type", "authorization_code");
            param.Add("redirect_uri", ConfigurationManager.AppSettings["WRedirect"]);
            param.Add("code", Code);
            string token = UcAsp.WorkFrame.UcAspWebClient.PostString("https://api.weibo.com/oauth2/access_token", param);
            JsonReader json = new JsonTextReader(new StringReader(token));
            JsonSerializer serializer = new JsonSerializer();
            UcAsp.Models.WeiboToken weibo = (UcAsp.Models.WeiboToken)serializer.Deserialize(json, typeof(UcAsp.Models.WeiboToken));
            string userinfo = UcAsp.WorkFrame.UcAspWebClient.GetString("https://api.weibo.com/2/users/show.json?access_token=" + weibo.access_token + "&uid=" + weibo.uid);
            JsonReader userjson = new JsonTextReader(new StringReader(userinfo));
            UcAsp.Models.WeiboUser weibouser = (UcAsp.Models.WeiboUser)serializer.Deserialize(userjson, typeof(UcAsp.Models.WeiboUser));

            UcAsp.Models.UserInfo info = entities.UserInfos.FirstOrDefault(o => o.OpenID == weibouser.id);
            if (info == null)
            {

                info = new Models.UserInfo { Point = Convert.ToInt32(UcAsp.WorkFrame.SettingConfig.GetSiteSetting.PointsRate), LoginIP = Request.UserHostAddress, RecommendID = 0, UserPassword = weibo.access_token, OpenID = weibo.uid, Remark=weibouser.remark, UserName = weibouser.screen_name, Logo = weibouser.avatar_large, SessionID = Session.SessionID, LoginTime = DateTime.Now };
                entities.UserInfos.Add(info);
                int id = entities.SaveChanges();
                Session["Info"] = "User";
                Session["ID"] = id.ToString();
                Session["UserName"] = info.UserName;

            }
            else
            {
                Session["Info"] = "User";
                Session["ID"] = info.ID;
                Session["UserName"] = info.UserName;
                info.UserPassword = weibo.access_token;
                info.Remark = weibouser.remark;
                info.OpenID = weibo.uid;
                info.Point = info.Point + 10;
                entities.SaveChanges();
            }
            return Redirect("/User/Home");

        }
    }
}
